// pages/test/index.js
const app = getApp();
const reqJs = require('../../utils/req.js');

Page({
  data: {
    projects: [],       
    giftProjects: [],   
    userInfo: null,     
    loading: true,      
    activeTab: 'project', 
    currentProject: null, 
    verifyCode: '',      
    showVerifyModal: false,
    selectedGift: null,   // 用户选择的礼品
    showExchangeConfirm: false, // 显示兑换确认框
    currentExchangeData: null // 当前兑换数据 {pid, gid, isLucky}
  },

  onLoad() {
    this.initData();
  },

  // 初始化数据
  async initData() {
    wx.showLoading({ title: '加载中...' });
    
    if (!app.globalData.openid) {
      try {
        await app.login();
      } catch (e) {
        console.error('登录失败', e);
        wx.hideLoading();
        return;
      }
    }
    
    try {
      // 获取项目列表
      const projectRes = await reqJs.getProjectList2();
      if (projectRes.code !== 200) throw new Error('获取项目列表失败');
      
      // 处理项目数据
      const projectMap = {};
      projectRes.data.forEach(p => {
        // 标记是否为幸运礼
        p.isLucky = p.play_name.includes('幸运礼') || p.play_name.includes('抽奖');
        projectMap[p.id] = p;
      });
      app.globalData.projectMap = projectMap;
      
      // 获取礼品库存
      const giftRes = await reqJs.getluckDrawStock();
      if (giftRes.code !== 200) throw new Error('获取礼品库存失败');
      
      // 处理礼品数据
      const giftStockMap = {};
      giftRes.data.forEach(gift => {
        if (!giftStockMap[gift.pid]) {
          giftStockMap[gift.pid] = [];
        }
        giftStockMap[gift.pid].push(gift);
      });
      app.globalData.giftStockMap = giftStockMap;
      
      // 获取用户信息
      const userInfo = await this.getUserInfo();
      app.globalData.userInfo = userInfo;
      
      // 合并数据
      const mergedProjects = this.mergeProjects(userInfo);
      const giftProjects = mergedProjects.filter(p => p.play_type === 4);
      
      this.setData({
        projects: mergedProjects,
        giftProjects: giftProjects,
        userInfo: userInfo,
        loading: false
      });
    } catch (e) {
      console.error('初始化失败', e);
      wx.showToast({
        title: '加载失败: ' + e.message,
        icon: 'none'
      });
      this.setData({ loading: false });
    }
    wx.hideLoading();
  },

  // 获取用户信息
  getUserInfo() {
    return new Promise((resolve, reject) => {
      app.getUser().then(res => {
        if (res.code === 200) {
          resolve(res.data);
        } else {
          reject(new Error(res.message || '获取用户信息失败'));
        }
      }).catch(reject);
    });
  },

  // 合并项目数据
  mergeProjects(userInfo) {
    const { projectMap, giftStockMap } = app.globalData;
    const userPlayList = userInfo.play_list || [];
    
    // 创建用户状态映射表
    const userStatusMap = {};
    userPlayList.forEach(item => {
      userStatusMap[item.pid] = {
        complete: item.complete,
        gid: item.gid
      };
    });
    
    // 生成最终数据
    return Object.values(projectMap).map(project => {
      const status = userStatusMap[project.id] || { 
        complete: 0, 
        gid: 0 
      };
      
      // 获取礼品信息
      let receivedGift = null;
      let gifts = giftStockMap[project.id] || [];
      
      if (status.gid && status.gid != 16) { // 排除未中奖情况
        receivedGift = gifts.find(g => g.gid === status.gid);
      }
      
      // 检查解锁条件
      const unlocked = this.checkCondition(project.condition, userInfo);
      
      return {
        ...project,
        ...status,
        gifts,
        receivedGift,
        unlocked
      };
    });
  },
  
  // 检查条件是否满足
  checkCondition(condition, userInfo) {
    if (!condition || !userInfo) return true;
    
    const userPlayList = userInfo.play_list || [];
    const userStatusMap = {};
    userPlayList.forEach(item => {
      userStatusMap[item.pid] = item.complete;
    });
    
    try {
      // 处理带括号的复杂条件
      const evaluateCondition = (expr) => {
        // 处理括号
        if (expr.includes('(')) {
          const inner = expr.match(/\(([^)]+)\)/)[1];
          const innerResult = evaluateCondition(inner);
          return evaluateCondition(expr.replace(`(${inner})`, innerResult ? '1' : '0'));
        }
        
        // 处理OR条件
        if (expr.includes('|')) {
          return expr.split('|').some(group => evaluateCondition(group));
        }
        
        // 处理AND条件
        if (expr.includes('&')) {
          return expr.split('&').every(pid => evaluateCondition(pid));
        }
        
        // 单个项目ID
        const pid = parseInt(expr.trim());
        return userStatusMap[pid] === 1;
      };
      
      return evaluateCondition(condition);
    } catch (e) {
      console.error('条件解析错误', e);
      return false;
    }
  },
  
  // 切换标签页
  switchTab(e) {
    this.setData({
      activeTab: e.currentTarget.dataset.tab
    });
  },
  
  // 打卡操作
  async handleCheckIn(e) {
    const pid = e.currentTarget.dataset.pid;
    const project = this.data.projects.find(p => p.id === pid);
    
    if (!project.unlocked) {
      wx.showToast({
        title: '未满足参与条件',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '打卡中...' });
    
    try {
      // 调用打卡接口
      const res = await reqJs.playGame({ pid });
      if (res.code !== 200) throw new Error(res.message || '打卡失败');
      
      // 刷新用户数据
      const userInfo = await this.getUserInfo();
      app.globalData.userInfo = userInfo;
      
      // 更新项目状态 - 增加解锁状态重新计算
      this.updateProjectStatus(pid, userInfo, true);
      
      wx.showToast({
        title: '打卡成功',
        icon: 'success'
      });
    } catch (e) {
      console.error('打卡失败', e);
      wx.showToast({
        title: e.message || '打卡失败',
        icon: 'none'
      });
    }
    wx.hideLoading();
  },
  
  // 选择礼品
  selectGift(e) {
    const pid = e.currentTarget.dataset.pid;
    const gid = e.currentTarget.dataset.gid;
    const project = this.data.projects.find(p => p.id === pid);
    const gift = project.gifts.find(g => g.gid === gid);
    
    this.setData({
      currentExchangeData: {
        pid,
        gid,
        isLucky: project.isLucky
      },
      showExchangeConfirm: true
    });
  },
  
  // 确认兑换
  async confirmExchange() {
    const { pid, gid, isLucky } = this.data.currentExchangeData;
    const project = this.data.projects.find(p => p.id === pid);
    
    if (!project.unlocked) {
      wx.showToast({
        title: '未满足参与条件',
        icon: 'none'
      });
      this.cancelExchange();
      return;
    }
    
    wx.showLoading({ title: isLucky ? '抽奖中...' : '兑换中...' });
    
    try {
      let res;
      // 幸运礼调用抽奖接口，普通兑换调用兑奖接口
      if (isLucky) {
        res = await reqJs.luckDraw({ pid, gid: 0 }); // 幸运礼不传gid
      } else {
        res = await reqJs.luckDraw({ pid, gid }); // 普通兑换传gid
      }
      
      if (res.code !== 200) throw new Error(res.message || (isLucky ? '抽奖失败' : '兑换失败'));
      
      // 处理未中奖情况 (gid=16)
      if (isLucky && res.data && res.data.gid === 16) {
        wx.showToast({
          title: '很遗憾，未中奖',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: isLucky ? '抽奖成功' : '兑换成功',
          icon: 'success'
        });
      }
      
      // 刷新用户数据
      const userInfo = await this.getUserInfo();
      app.globalData.userInfo = userInfo;
      
      // 更新项目状态
      this.updateProjectStatus(pid, userInfo);
      
    } catch (e) {
      console.error(isLucky ? '抽奖失败' : '兑换失败', e);
      wx.showToast({
        title: e.message || (isLucky ? '抽奖失败' : '兑换失败'),
        icon: 'none'
      });
    }
    
    this.cancelExchange();
    wx.hideLoading();
  },
  
  // 取消兑换
  cancelExchange() {
    this.setData({
      showExchangeConfirm: false,
      currentExchangeData: null
    });
  },
  
  // 打开核销模态框
  openVerifyModal(e) {
    const pid = e.currentTarget.dataset.pid;
    const project = this.data.projects.find(p => p.id === pid);
    
    // 确保已兑换且不是未中奖状态
    if (!project.receivedGift || project.gid === 16) {
      wx.showToast({
        title: '无可用礼品',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      currentProject: project,
      showVerifyModal: true,
      verifyCode: ''
    });
  },
  
  // 关闭核销模态框
  closeVerifyModal() {
    this.setData({
      showVerifyModal: false,
      currentProject: null
    });
  },
  
  // 输入核销码
  inputVerifyCode(e) {
    this.setData({
      verifyCode: e.detail.value
    });
  },
  
  // 提交核销
  async submitVerify() {
    const { currentProject, verifyCode } = this.data;
    if (!verifyCode) {
      wx.showToast({
        title: '请输入核销码',
        icon: 'none'
      });
      return;
    }
    
    if (!currentProject || !currentProject.receivedGift) {
      wx.showToast({
        title: '未选择礼品',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '核销中...' });
    
    try {
      // 调用核销接口 - 传递正确的gid
      const res = await reqJs.getGift({
        pid: currentProject.id,
        gid: currentProject.receivedGift.gid,
        code: verifyCode
      });
      
      if (res.code !== 200) throw new Error(res.message || '核销失败');
      
      // 刷新用户数据
      const userInfo = await this.getUserInfo();
      app.globalData.userInfo = userInfo;
      
      // 更新当前项目状态
      this.updateProjectStatus(currentProject.id, userInfo, true);
      
      this.closeVerifyModal();
      wx.showToast({
        title: '核销成功',
        icon: 'success'
      });
    } catch (e) {
      console.error('核销失败', e);
      wx.showToast({
        title: e.message || '核销失败',
        icon: 'none'
      });
    }
    wx.hideLoading();
  },
  
  // 更新项目状态
  updateProjectStatus(pid, userInfo, updateAll = false) {
    let { projects } = this.data;
    const index = projects.findIndex(p => p.id === pid);
    
    if (index !== -1) {
      // 创建用户状态映射表
      const userStatusMap = {};
      userInfo.play_list.forEach(item => {
        userStatusMap[item.pid] = {
          complete: item.complete,
          gid: item.gid
        };
      });
      
      // 更新项目状态
      const status = userStatusMap[pid] || { complete: 0, gid: 0 };
      let receivedGift = null;
      
      // 处理未中奖情况 (gid=16)
      if (status.gid && status.gid != 16) {
        const gifts = app.globalData.giftStockMap[pid] || [];
        receivedGift = gifts.find(g => g.gid === status.gid);
      }
      
      const newProjects = [...projects];
      newProjects[index] = {
        ...newProjects[index],
        ...status,
        receivedGift
      };
      
      // 如果需要更新所有项目的解锁状态
      if (updateAll) {
        newProjects.forEach(project => {
          project.unlocked = this.checkCondition(project.condition, userInfo);
        });
      }
      
      // 更新礼品项目列表
      const giftProjects = newProjects.filter(p => p.play_type === 4);
      
      this.setData({
        projects: newProjects,
        giftProjects: giftProjects,
        userInfo: userInfo
      });
    }
  },
  
  // 刷新数据
  async refreshData() {
    this.setData({ loading: true });
    try {
      // 清空缓存
      app.globalData.projectMap = null;
      app.globalData.giftStockMap = {};
      
      // 重新加载数据
      await this.initData();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    } catch (e) {
      console.error('刷新失败', e);
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },
  
  // 获取项目类型名称
  getPlayTypeName(type) {
    const types = {
      1: '体验/打卡',
      2: '闯关/完成项目',
      3: '直接兑奖项目',
      4: '兑换/核销奖品',
      5: '留资项目'
    };
    return types[type] || '未知类型';
  },
  
  // 获取礼品状态文本
  getGiftStatusText(project) {
    if (!project.unlocked) return '未解锁';
    
    if (project.complete) {
      if (project.gid === 16) return '未中奖';
      if (project.receivedGift) return project.receivedGift ? '已兑换' : '已核销';
    }
    
    return '立即兑换';
  }
});